package dome1.network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException{
        System.out.println("服务器启动！");

        //1、手动链接服务器
        /*while (true) {
            Socket clientSocket = serverSocket.accept();

            //代码改成多线程的形式，就不能通过try()的方式来关闭clientSocket了
            //否则前一个clientSocket还在使用，后面再来一个线程就会立即关闭
            Thread t = new Thread(() -> {
                try{
                    //通过processConnection方法处理每一次连接
                    processConnection(clientSocket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            t.start();
        }*/
        //2、采用线程池的方式来链接服务器
        ExecutorService pool = Executors.newCachedThreadPool();
        while (true) {
            Socket clientSocket = serverSocket.accept();
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        //通过processConnection方法处理每一次连接
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    private void processConnection(Socket clientSocket) throws IOException {

        //1、打印一个日志，告知说当前有客户端连上了
        //(IP和端口)
        System.out.printf("[%s:%d] 客户端上线！\n", clientSocket.getInetAddress(), clientSocket.getPort());

        //2、从socket中获取到流对象，来进一步的进行后续操作
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){

            //3、循环 因为针对每个连接，客户端都可能发来多个请求，服务器也就需要通过这段代码返回多个响应
            Scanner scanner = new Scanner(inputStream);
            while(true) {
                //3.1读取内容并解析
                //判断是否读取到了下一个
                if(!scanner.hasNext()) {
                    //如果发现后续没有数据了，就结束循环说明此时TCP是断开连接的
                    System.out.printf("[%s:%d] 客户端下线! \n",clientSocket.getInetAddress(), clientSocket.getPort());
                    break;
                }
                String request = scanner.next();

                //3.2、根据请求在回显服务器里计算响应并返回
                String response = process(request);

                //3.3、把响应返回给客户端
                outputStream.write(response.getBytes(),0,response.getBytes().length);

                //3.4、服务器打印日志
                //请求的IP地址，端口号，请求，响应；
                System.out.printf("[%s:%d] req=%s, resp=%s\n",clientSocket.getInetAddress(),clientSocket.getPort(),request,response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            clientSocket.close();
        }
    }

    public String process(String request) {
        //给响应加一个换行符，使客户端读取响应的时候，也有分隔符
        return request + "\n";
    }

    //回显服务器
    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}
